package es.xpt.ysf.commons.pos;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.URL;

import es.xpt.ysf.configuration.Configuration;


public class PosBBVADispatcher extends HttpServlet { // NO_UCD
	private static final long serialVersionUID = 1L;
	
    public PosBBVADispatcher() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		perform(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		perform(request,response);		
	}	
	
	private void perform (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Hashtable<String, String> parameters = loadSpecialParameters(request);
		String action = (String)request.getParameter("action");
		String petition = (String)request.getParameter("peticion");
		if (petition==null) { 
			if (action==null)
				action=parameters.get("action");
			
			if (action!=null && action.trim().equals("dispatch")) {
				dispatchBBVA(request,response);
			}
			
			if (action!=null && action.trim().equals("dispatchPost")) {
				dispatchBBVAPost(request, response);
			}
			
			if (action!=null && action.trim().equals("OK")) {
				dispatchOKKO(request,response,"OK_NOTIFICATION", parameters);
			}
			
			if (action!=null && action.trim().equals("KO")) {
				dispatchOKKO(request,response,"KO", parameters);
			}
		} else {
			//Es la notificacion
			System.err.println(petition);
			if (petition.contains("<estado>2</estado>")) {
				//Todo OK				
				notifyTransaction(petition,request);
			} 
		}
	}	
	
	private void notifyTransaction(String petition, HttpServletRequest request) {
		
		if (petition.contains("<idtransaccion>")) {
			String price = petition.substring(petition.indexOf("<importe>")+9, petition.indexOf("</importe>"));
			String bookingReference = calculateBookingRefence(petition.substring(petition.indexOf("<idtransaccion>")+15, petition.indexOf("</idtransaccion>")));
			bookingReference = bookingReference.substring(0, bookingReference.length()-1)+"_"+bookingReference.substring(bookingReference.length()-1); 
			String url = "http://"+request.getLocalAddr()+":"+request.getLocalPort()+request.getContextPath()+"/dynamic/BookingReader/reconfirmBooking.faces";
			url+="?action=OK&operationNumber="+bookingReference+"&price="+replaceNoNum(price);
			URLConnection urlcon=null;
			try {			
				urlcon = new URL(url).openConnection();
				urlcon.getContent();
			
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally{				
				urlcon=null;
			}
		}
		
	}
	
	public static String calculateBookingRefence(String cadena)
    {
        StringBuffer buffer = new StringBuffer(cadena);
        int cont = 0;
        while (cont < buffer.length())
        {
            if (buffer.charAt(cont)=='0')
            {
                buffer.deleteCharAt(cont);                
            } else {
            	break;
            }
                
        }
        return buffer.toString();
    }

	/**
     * Devuelve el String resultante de eliminar del String pasado 
     * como parmetro los caracteres que no son numricos.
     */
    public static String replaceNoNum(String cadena)
    {
        StringBuffer buffer = new StringBuffer(cadena);
        int cont = 0;
        while (cont < buffer.length())
        {
            if (!Character.isDigit(buffer.charAt(cont)))
            {
                buffer.deleteCharAt(cont);
            }
            else
                cont++;
        }
        return buffer.toString();
    }
    
	private Hashtable<String, String> loadSpecialParameters(HttpServletRequest request) {
		String special = (String)request.getParameter("params");
		if (special!=null) {
			Hashtable<String, String> parameters = new Hashtable<String, String>();
			String[] params = special.split("-");
			
			for (String s:params) {
				String individualParam[] = s.split("=");
				parameters.put(individualParam[0], individualParam[1]);
			}
			return parameters;
		}
		return null;
	}

	private void dispatchOKKO(HttpServletRequest request,
			HttpServletResponse response,String action,
			Hashtable<String, String> parameters) throws IOException {
		String environment = parameters.get("env");
		String app = parameters.get("app");
		String operationNumber = parameters.get("bookingReference");		
		String price = parameters.get("price");
		String module = "modules."+app+".urlBBVAReturn";
		String url = (new Configuration (environment)).getString(module);
		url+="?action="+action+"&operationNumber="+operationNumber+"&price="+price;;
		response.sendRedirect(url);		
	}
	
	private void dispatchBBVA(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		String url = (String)request.getParameter("urlPos");
		response.sendRedirect(url);
				
	}
	
	private void dispatchBBVAPost(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		String url = (String)request.getParameter("urlPos");
		if (url==null || url.equals("")) {
			url = (String)request.getAttribute("urlPos");
		}
		PrintWriter pw = response.getWriter();
		pw.write( url );
		pw.flush();
		pw.close();

				
	}
}
